package dao.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import dao.IGenericDao;

@Repository
public class GenericDao<T> implements IGenericDao<T> {

	@Autowired
	private HibernateTemplate hibernateTemplate;

	public void save(T entity) {
		hibernateTemplate.save(entity);
	}

	public void delete(T entity) {
		hibernateTemplate.delete(entity);
	}

	@SuppressWarnings("unchecked")
	public T get(Integer id) {
		return (T) hibernateTemplate.load(getEntityClass(), id);
	}

	@SuppressWarnings("unchecked")
	public List<T> getAll() {
		String queryString = "FROM " + getEntityClass();
		Query query = getSession().createQuery(queryString);

		return query.list();
	}

	protected Session getSession() {
		return hibernateTemplate.getSessionFactory().getCurrentSession();
	}

	@SuppressWarnings("unchecked")
	private Class<T> getEntityClass() {
		return (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

	public void saveOrUpdate(T entity) {
		hibernateTemplate.saveOrUpdate(entity);
	}
}